package com.itheima.aop;

import com.alibaba.fastjson2.JSON;
import com.itheima.entity.OperateLog;
import com.itheima.service.LogPrintService;
import com.itheima.util.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
//@Component
@Slf4j
@Aspect
public class RecordLogAspect {
    @Autowired
    private LogPrintService logPrintService;
    @Around("@annotation(recordLog)")
    public Object around(ProceedingJoinPoint pjp,RecordLog recordLog)throws Throwable{
        //需要提供接口，对UserThreadLocal  解耦
        UserThreadLocal.UserInfo userInfo = UserThreadLocal.getUserInfo();
        Integer id = userInfo.getId();
        String username = userInfo.getName();


        // 从pjp中获取类名、执行方法名、方法运行时参数、返回值
        Signature signature = pjp.getSignature();
        String  className = signature.getDeclaringTypeName();
        String methodName = signature.getName();
        Object[] args = pjp.getArgs();
        long start = System.currentTimeMillis();

        Object result = null;
        long costTime = 0;

        try {
            result = pjp.proceed();
            long end = System.currentTimeMillis();
            costTime = end-start;
        }finally {
            OperateLog log = OperateLog.builder()
                    .operateUser(id)
                    .operateName(username)
                    .costTime(costTime)
                    .className(className)
                    .methodName(methodName)
                    .methodDesc(recordLog.desc())
                    .methodParams(args == null ? "" : JSON.toJSONString(args))
                    .returnValue(result == null ? "" : JSON.toJSONString(result))
                    .operateTime(LocalDateTime.now())
                    .build();
            logPrintService.printLog(log);
        }

        return result;

    }

}
